package com.tracesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tracesystem.commons.Result;
import com.tracesystem.controller.form.UserMenusForm;
import com.tracesystem.controller.info.MenusListInfo;
import com.tracesystem.dao.IssueMenusRoleDao;
import com.tracesystem.model.IssueMenus;
import com.tracesystem.dao.IssueMenusDao;
import com.tracesystem.model.IssueMenusRole;
import com.tracesystem.service.IssueMenusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tracesystem.util.WoniuCopyUtil;
import com.tracesystem.util.exception.MenusException;
import com.tracesystem.util.exception.code.MenusExceptionCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-23
 */
@Service
public class IssueMenusServiceImpl extends ServiceImpl<IssueMenusDao, IssueMenus> implements IssueMenusService {
    @Resource
    private IssueMenusRoleDao menusRoleDao;


    @Override
    public Result<List<MenusListInfo>> getMenus(UserMenusForm userMenusForm) {
        List<IssueMenusRole> roleMenuList = menusRoleDao.selectList(new QueryWrapper<IssueMenusRole>().eq("ROLE_ID", userMenusForm.getRoleId()));
        if (null == roleMenuList || roleMenuList.size() == 0) {
            throw new MenusException(MenusExceptionCode.Menus_NOTFIND_EXCEPTION);
        }
        List<Integer> collect = roleMenuList.stream().map(rm -> rm.getMenusId()).collect(Collectors.toList());
        List<IssueMenus> issueMenus = listByIds(collect);
        List<MenusListInfo> menusListInfos = WoniuCopyUtil.copyMany(issueMenus, MenusListInfo.class);
        Map<Integer, MenusListInfo> mp = new HashMap<>();
        List<MenusListInfo> listInfos = new ArrayList<MenusListInfo>();
        for (MenusListInfo menusListInfo : menusListInfos) {
            mp.put(menusListInfo.getMenusId(), menusListInfo);
        }
        for (MenusListInfo menusListInfo : menusListInfos) {
            if (menusListInfo.getMenusParentid() == 0) {
                listInfos.add(menusListInfo);
            } else {
                if (mp.get(menusListInfo.getMenusParentid()).getChildren() == null)
                    mp.get(menusListInfo.getMenusParentid()).setChildren(new ArrayList<MenusListInfo>());
                mp.get(menusListInfo.getMenusParentid()).getChildren().add(menusListInfo);

            }

        }
        return Result.getInstanceList(MenusListInfo.class).setData(listInfos);
    }
}
